var async = require("async");
var renderEngin = require("../common/renderEngin");
var Tools = require("../common/tools");
function getQueryString(req) {
    return require("querystring").parse(require("url").parse(req.url).query);
}
exports.orders = function (req, res) {
    use([
        "public/javascripts/orders/init.js",
        "public/javascripts/service/ordersService.js"
    ], function (PageComponent, ordersService) {
        var param = getQueryString(req);
        var storage = {};
        storage["slider"] = Tools.getPageSliderData("user_center");
        storage["query"] = param;

        /**
         * 根据产品Id获取产品基本信息
         */
        function getProductById(done) {
            var config = {
                headers: req.headers,
                'seatParams': {
                    id: param.id || param.productId
                }
            };
            ordersService.getProductById(config, function (result) {
                if (result.errorCode === 0) {
                    done(null, result.data);
                } else {
                    done(null, {});
                }
            });
        }

        /**
         * 获取计量单位
         * @param done
         */
        function getUnit(done){
            var config = {
                headers: req.headers
            };
            ordersService.getUnitbase(config, function (result) {
                if (result.errorCode === 0) {
                    done(null, result.data);
                } else {
                    done(null, {});
                }
            });
        }

        /**
         * 根据订单oid获取订单详情
         * @param done
         */
        function getOrderByOid(done) {
            var config = {
                headers: req.headers,
                seatParams: {
                    'orderNo': param.oid
                }
            };
            ordersService.getOrderByOid(config, function (result) {
                if (result.errorCode === 0) {
                    var config = {
                        headers: req.headers,
                        'seatParams': {
                            id: result.data.productId
                        }
                    };
                    ordersService.getProductById(config, function (results) {
                        result.data.productInfo = results.data || {};

                        ordersService.getProGroupRootId({
                            headers: req.headers,
                            'seatParams': {
                                'productId': result.data.productId
                            }
                        }, function (groupResults) {
                            if (groupResults.errorCode === 0) {
                                result.data.productGroupRootId = groupResults.data.productGroupRootId;
                                result.data.currencyCode = groupResults.data.currencyCode;
                            }
                            done(null, result.data);
                        });
                    });
                } else {
                    done(null, {'productInfo': {}, 'orderInfo': {}});
                }
            });
        }

        /**
         * 根据订单oid获取订单物流信息
         * @param done
         */
        function getOrderLogistics(done) {
            var config = {
                headers: req.headers,
                urlParams: [param.oid]
            };
            ordersService.getOrderLogistics(config, function (result) {
                if (result.errorCode === 0) {
                    done(null, result.data);
                } else {
                    done(null, {});
                }
            });
        }

        /**
         * 批量下单，根据订单HighVolumeOrderId获取订单物流信息,然后根据productId获取产品信息，注意后续要处理产品信息不是空的情况
         * @param done
         */
        function getOrderByHighVolumeOrderId(done) {
            console.log(param.highVolumeOrderId);
            var config = {
                headers: req.headers,
                seatParams: {"id":param.highVolumeOrderId}
            };

            ordersService.getOrderByHighVolumeOrderId(config, function (result) {


                result.data.orderBatchDetailDto.errorDtoMap = result.data.errorDtoMap;
                result.data.orderBatchDetailDto.productInfo = null;

                //先用假的数据

                if (result.errorCode === 0 && result.data.orderBatchDetailDto.productId) {

                    var config = {
                        headers: req.headers,
                        'seatParams': {
                            id: result.data.orderBatchDetailDto.productId
                        }
                    };

                    ordersService.getProductById(config, function (res) {


                        result.data.orderBatchDetailDto.productInfo = res.data || null;

                        ordersService.getProGroupRootId({
                            headers: req.headers,
                            'seatParams': {
                                'productId': result.data.orderBatchDetailDto.productId
                            }
                        }, function (groupResults) {
                            if (groupResults.errorCode === 0) {
                                result.data.orderBatchDetailDto.productGroupRootId = groupResults.data.productGroupRootId;
                                result.data.orderBatchDetailDto.currencyCode = groupResults.data.currencyCode;
                            }
                            done(null, result.data.orderBatchDetailDto);
                        });

                    });

                }else{
                    done(null, result.data.orderBatchDetailDto);
                }


            });
        }

        function rebuildName(originOne,addOne) {
            if(originOne && addOne) {
                return originOne+'('+addOne + ')';
            }
            if(originOne && !addOne){
                return originOne;
            }

            if(!originOne && addOne){
                return addOne
            }
            return '';

        }


        if(param.highVolumeOrderId){ //从批量下单过来的数据，这里要把错误信息也分开传进去
            async.parallel({
                product: getOrderByHighVolumeOrderId,
                unit:getUnit
            }, function (err, result) {
                if (storage) {

                    //物流信息
                    storage["logistics"] = {};

                    //产品及基本信息
                    storage["product"] = result.product || {};

                    //物品信息
                    var orderCargoDtos = [{
                        description: '',
                        goodsNameCn: '',
                        goodsNameEn: '',
                        goodsNumber: '',
                        goodsPrice: '',
                        goodsUnit: 'pieces',
                        goodsUnitName: '件',
                        hsCode: '',
                        id: ''
                    }];

                    var shipping = 1; //港口
                    var airport = 6;  //海运
                    var otherTransport = 11; //其余

                    storage["goods"] = result.product.cargos.length ? result.product.cargos: orderCargoDtos; //注意这里和之前处理不同，现在没有值也会传空数组

                    //地址信息
                    if (result.product.fetchAddress) {
                        result.product.fetchAddress.countryName = rebuildName( result.product.fetchAddress.countryName, result.product.fetchAddress.countryCode)
                    }

                    if (result.product.fromAddress) {
                        result.product.fromAddress.countryName = rebuildName(result.product.fromAddress.countryName,result.product.fromAddress.countryCode)

                        if (result.product.productGroupRootId == shipping) {
                            result.product.fromAddress.transportName = rebuildName(result.product.fromAddress.transportName,result.product.fromAddress.transportEnglishName)
                        } else if (result.product.productGroupRootId == airport) {
                            result.product.fromAddress.transportName = rebuildName(result.product.fromAddress.transportName,result.product.fromAddress.transportCode)
                        }
                    }
                    if (result.product.toAddress) {
                        result.product.toAddress.countryName = rebuildName(result.product.toAddress.countryName,result.product.toAddress.countryCode);

                        if (result.product.productGroupRootId == shipping) {
                            result.product.toAddress.transportName = rebuildName(result.product.toAddress.transportName,result.product.toAddress.transportEnglishName)

                        } else if (result.product.productGroupRootId == airport) {
                            result.product.toAddress.transportName = rebuildName(result.product.toAddress.transportName,result.product.toAddress.transportCode)
                        }
                    }

                    storage["address"] = {
                        'fetchAddress': result.product.fetchAddress || {},
                        'fetchDetail': result.product.fetchDetail,
                        'fetchName': result.product.fetchName,
                        'fetchPhone': result.product.fetchPhone,
                        'fetchTelephone': result.product.fetchTelephone,
                        'fetchSynShow': false,
                        'fromAddress': result.product.fromAddress || {},
                        'fromDetail': result.product.fromDetail,
                        'fromName': result.product.fromName,
                        'fromPhone': result.product.fromPhone,
                        'fromTelephone': result.product.fromTelephone,
                        'fromSynShow': false,
                        'toAddress': result.product.toAddress || {},
                        'toDetail': result.product.toDetail,
                        'toName': result.product.toName,
                        'toPhone': result.product.toPhone,
                        'toTelephone': result.product.toTelephone,
                        'toSynShow': false,
                        'optionalService': result.product.orderAdditionalDtos || []
                    };


                    //预估费用
                    storage["cost"] = result.product.cost || '';

                    //附件信息
                    storage["annex"] = result.product.fileDtos || [];

                    //客户留言
                    storage["message"] = result.product.customerNote || '';

                    //订单状态
                    storage["status"] = {
                        'orderStatus': result.product.orderStatus || '',
                        'orderStatusName': result.product.orderStatusName || ''
                    };

                    //子单信息
                    storage["suborder"] = result.product.ordSubOrderDtos || [];

                    //存放公共信息
                    storage["info"] = {};

                    // 一定是草稿状态
                    storage["info"].isEdit = true;
                    storage['info'].oid = param.oid;
                    storage['info'].waybillNo = result.product.waybillNo;
                    storage['info'].productId = result.product.productId;
                    storage['info'].productUid = result.product.productUid;
                    storage['info'].from = 'highVolumeOrders';    //从订单界面过来

                    storage['info'].unit = result.unit || [];
                    //  用于返回原来的批量下单界面使用
                    storage['info'].highVolumeOrderId = param.highVolumeOrderId;
                    storage['info'].batchNumber = param.batchNumber;
                    storage['info'].batchNumber = param.batchNumber;
                    storage['info'].pageSize = param.pageSize;
                    storage['info'].pageIndex = param.pageIndex;
                    storage['info'].q = param.q;
                    storage['info'].verifiedStatus = param.verifiedStatus;

                    //  用于记录错误的信息
                    storage['info'].errorDtoMap = result.product.errorDtoMap;

                    PageComponent = React.createFactory(PageComponent);
                    renderEngin.call(res, 'orders', PageComponent, storage);
                }
            });
        }else if(param.oid) { //订单列表点击某个订单
            async.parallel({
                product: getOrderByOid,
                unit:getUnit,
                logistics: getOrderLogistics
            }, function (err, result) {
                if (storage) {
                    //物流信息
                    storage["logistics"] = result.logistics || {};

                    //产品及基本信息
                    storage["product"] = result.product || {};

                    //物品信息
                    var orderCargoDtos = [{
                        description: '',
                        goodsNameCn: '',
                        goodsNameEn: '',
                        goodsNumber: '',
                        goodsPrice: '',
                        goodsUnit: 'pieces',
                        goodsUnitName: '件',
                        hsCode: '',
                        id: ''
                    }];
                    storage["goods"] = result.product.orderCargoDtos || orderCargoDtos;

                    //地址信息
                    if (result.product.fetchAddress) {
                        result.product.fetchAddress.countryName += '(' + result.product.fetchAddress.countryCode + ')';
                    }

                    if (result.product.fromAddress) {
                        result.product.fromAddress.countryName += '(' + result.product.fromAddress.countryCode + ')';

                        if (result.product.productGroupRootId == 1) {
                            result.product.fromAddress.transportName += '(' + result.product.fromAddress.transportEnglishName + ')';
                        } else if (result.product.productGroupRootId == 6) {
                            result.product.fromAddress.transportName += '(' + result.product.fromAddress.transportCode + ')';
                        }
                    }
                    if (result.product.toAddress) {
                        result.product.toAddress.countryName += '(' + result.product.toAddress.countryCode + ')';

                        if (result.product.productGroupRootId == 1) {
                            result.product.toAddress.transportName += '(' + result.product.toAddress.transportEnglishName + ')';
                        } else if (result.product.productGroupRootId == 6) {
                            result.product.toAddress.transportName += '(' + result.product.toAddress.transportCode + ')';
                        }
                    }

                    storage["address"] = {
                        'fetchAddress': result.product.fetchAddress || {},
                        'fetchDetail': result.product.fetchDetail,
                        'fetchName': result.product.fetchName,
                        'fetchPhone': result.product.fetchPhone,
                        'fetchTelephone': result.product.fetchTelephone,
                        'fetchSynShow': false,
                        'fromAddress': result.product.fromAddress || {},
                        'fromDetail': result.product.fromDetail,
                        'fromName': result.product.fromName,
                        'fromPhone': result.product.fromPhone,
                        'fromTelephone': result.product.fromTelephone,
                        'fromSynShow': false,
                        'toAddress': result.product.toAddress || {},
                        'toDetail': result.product.toDetail,
                        'toName': result.product.toName,
                        'toPhone': result.product.toPhone,
                        'toTelephone': result.product.toTelephone,
                        'toSynShow': false,
                        'optionalService': result.product.orderAdditionalDtos || []
                    };

                    //预估费用
                    storage["cost"] = result.product.cost || '';

                    //附件信息
                    storage["annex"] = result.product.fileDtos || [];

                    //客户留言
                    storage["message"] = result.product.customerNote || '';

                    //订单状态
                    storage["status"] = {
                        'orderStatus': result.product.orderStatus || '',
                        'orderStatusName': result.product.orderStatusName || ''
                    };

                    //子单信息
                    storage["suborder"] = result.product.ordSubOrderDtos || [];

                    //存放公共信息
                    storage["info"] = {};
                    if (result.product.orderStatus && result.product.orderStatus.toUpperCase() == 'DRAFT') {
                        storage["info"].isEdit = true;
                    } else {
                        storage["info"].isEdit = false;
                    }
                    storage['info'].oid = param.oid;
                    storage['info'].waybillNo = result.product.waybillNo;
                    storage['info'].productId = result.product.productId;
                    storage['info'].productUid = result.product.productUid;
                    storage['info'].from = 'orders';    //从订单界面过来
                    storage['info'].unit = result.unit || [];


                    PageComponent = React.createFactory(PageComponent);
                    renderEngin.call(res, 'orders', PageComponent, storage);
                }
            });
        } else if (param.id) {    //从下单过来的数据
            async.parallel({
                product: getProductById,
                unit:getUnit
            }, function (err, result) {
                if (storage) {
                    //产品及基本信息
                    storage['product'] = {
                        'productInfo': result.product
                    };

                    //物品信息
                    storage["goods"] = [{
                        description: '',
                        goodsNameCn: '',
                        goodsNameEn: '',
                        goodsNumber: '',
                        goodsPrice: '',
                        goodsUnit: 'pieces',
                        goodsUnitName: '件',
                        hsCode: '',
                        id: ''
                    }];

                    //物流信息
                    storage["logistics"] = [];

                    //地址信息，地址信息需要请求接口获取第一个可选地址信息。
                    var optionalService = [];
                    if (param.serviceids) {
                        param.serviceids.split(',').forEach(function (item, index) {
                            optionalService.push({'serviceTypeCode': item});
                        });
                    }
                    storage["address"] = {
                        'fetchAddress': result.product.fetchAddress || {},
                        'fetchDetail': result.product.fetchDetail,
                        'fetchName': result.product.fetchName,
                        'fetchPhone': result.product.fetchPhone,
                        'fetchTelephone': result.product.fetchTelephone,
                        'fetchSynShow': true,
                        'fromAddress': result.product.fromAddress || {},
                        'fromDetail': result.product.fromDetail,
                        'fromName': result.product.fromName,
                        'fromPhone': result.product.fromPhone,
                        'fromTelephone': result.product.fromTelephone,
                        'fromSynShow': true,
                        'toAddress': result.product.toAddress || {},
                        'toDetail': result.product.toDetail,
                        'toName': result.product.toName,
                        'toPhone': result.product.toPhone,
                        'toTelephone': result.product.toTelephone,
                        'toSynShow': true,
                        'optionalService': optionalService
                    };

                    //预估费用
                    storage["cost"] = '';

                    //附件信息
                    storage["annex"] = [];

                    //客户留言
                    storage["message"] = '';

                    //订单状态
                    storage["status"] = {
                        'orderStatus': '',
                        'orderStatusName': ''
                    };

                    //子单信息
                    storage["suborder"] = [];

                    //存放公共信息
                    storage["info"] = {};
                    if (result.product.orderStatus && result.product.orderStatus.toUpperCase() == 'DRAFT') {
                        storage["info"].isEdit = true;
                    } else {
                        storage["info"].isEdit = false;
                    }

                    storage['info'].serviceids = optionalService;
                    storage['info'].productId = result.product.id;
                    storage['info'].productUid = result.product.uid;
                    storage['info'].from = 'product';    //从下单界面过来
                    storage['info'].unit = result.unit || [];

                    PageComponent = React.createFactory(PageComponent);
                    renderEngin.call(res, 'orders', PageComponent, storage);
                }
            });
        } else if (param.pageName == 'feeTrial') {    //运费试算
            async.parallel({
                product: getProductById,
                unit:getUnit
            }, function (err, result) {
                if (storage) {
                    //产品及基本信息
                    storage['product'] = {
                        'productInfo': result.product
                    };

                    //物品信息
                    storage["goods"] = [{
                        description: '',
                        goodsNameCn: '',
                        goodsNameEn: '',
                        goodsNumber: '',
                        goodsPrice: '',
                        goodsUnit: 'pieces',
                        goodsUnitName: '件',
                        hsCode: '',
                        id: ''
                    }];

                    //物流信息
                    storage["logistics"] = [];

                    //地址信息，地址信息需要请求接口获取第一个可选地址信息。
                    var optionalService = [];
                    if (param.serviceids) {
                        param.serviceids.split(',').forEach(function (item, index) {
                            optionalService.push({'serviceTypeCode': item});
                        });
                    }
                    storage["address"] = {
                        'fetchAddress': result.product.fetchAddress || {},
                        'fetchDetail': result.product.fetchDetail,
                        'fetchName': result.product.fetchName,
                        'fetchPhone': result.product.fetchPhone,
                        'fetchTelephone': result.product.fetchTelephone,
                        'fetchSynShow': true,
                        'fromAddress': result.product.fromAddress || {},
                        'fromDetail': result.product.fromDetail,
                        'fromName': result.product.fromName,
                        'fromPhone': result.product.fromPhone,
                        'fromTelephone': result.product.fromTelephone,
                        'fromSynShow': true,
                        'toAddress': result.product.toAddress || {},
                        'toDetail': result.product.toDetail,
                        'toName': result.product.toName,
                        'toPhone': result.product.toPhone,
                        'toTelephone': result.product.toTelephone,
                        'toSynShow': true,
                        'optionalService': optionalService
                    };

                    //预估费用
                    storage["cost"] = '';

                    //附件信息
                    storage["annex"] = [];

                    //客户留言
                    storage["message"] = '';

                    //订单状态
                    storage["status"] = {
                        'orderStatus': '',
                        'orderStatusName': ''
                    };

                    //子单信息
                    storage["suborder"] = [];

                    //存放公共信息
                    storage["info"] = {};
                    if (result.product.orderStatus && result.product.orderStatus.toUpperCase() == 'DRAFT') {
                        storage["info"].isEdit = true;
                    } else {
                        storage["info"].isEdit = false;
                    }

                    storage['info'].serviceids = optionalService;
                    storage['info'].productId = result.product.id;
                    storage['info'].productUid = result.product.uid;
                    storage['info'].from = 'feeTrial';    //从运费试算界面过来
                    storage['info'].unit = result.unit || [];
                    PageComponent = React.createFactory(PageComponent);
                    renderEngin.call(res, 'orders', PageComponent, storage);
                }
            });
        }
    });
};
